<template>
  <div class="category">
    <h1 class="page-title">{{ categoryName }} 分类下的文章</h1>
    
    <div class="article-list" v-if="articles.length > 0">
      <ArticleCard 
        v-for="(article, index) in articles" 
        :key="article.id"
        :article="article"
        :isReverse="index % 2 !== 0"
        @click="handleArticleClick"
      />
    </div>
    
    <div class="empty" v-else>
      <p>该分类下暂无文章</p>
    </div>
    
    <div class="pagination" v-if="total > 0">
      <a-pagination
        :current="current"
        :total="total"
        :pageSize="pageSize"
        @change="handlePageChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getArticlesByCategory } from '@/api/article';
import ArticleCard from '@/components/ArticleCard.vue';
import { useCategoryStore } from '@/stores/category';

const route = useRoute();
const router = useRouter();
const categoryStore = useCategoryStore();
const articles = ref([]);
const categoryName = ref('');
const current = ref(1);
const pageSize = ref(6);
const total = ref(0);

const fetchCategoryArticles = async () => {
  const categoryId = parseInt(route.params.id as string);
  try {
    const res = await getArticlesByCategory(categoryId, current.value, pageSize.value);
    articles.value = res.records;
    total.value = res.total;
    
    // 设置分类名称
    const category = categoryStore.categories.find(c => c.id === categoryId);
    if (category) {
      categoryName.value = category.name;
    }
  } catch (error) {
    console.error('获取分类文章失败:', error);
  }
};

onMounted(async () => {
  // 先获取所有分类
  if (categoryStore.categories.length === 0) {
    await categoryStore.fetchCategories();
  }
  fetchCategoryArticles();
});

// 监听路由变化，切换分类时重新获取文章
watch(() => route.params.id, () => {
  current.value = 1;
  fetchCategoryArticles();
});

const handlePageChange = (page: number) => {
  current.value = page;
  fetchCategoryArticles();
};

const handleArticleClick = (article: any) => {
  router.push(`/article/${article.id}`);
};
</script>

<style scoped>
.category {
  padding: 20px;
}

.page-title {
  margin-bottom: 30px;
  color: #333;
  text-align: center;
  font-size: 2rem;
  position: relative;
}

.page-title:after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 3px;
  background: linear-gradient(to right, #42b983, #64b5f6);
}

.article-list {
  margin: 40px 0;
}

.empty {
  text-align: center;
  padding: 50px;
  color: #999;
  font-size: 1.1rem;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
</style> 